//
//  LKBaseViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/4/9.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKBaseViewController.h"
@implementation LKNavBackButton

- (void)setTitleColor:(UIColor *)titleColor
{
    _titleColor = titleColor;
    [self setTitleColor:titleColor forState:UIControlStateNormal];
}

+ (instancetype)navBackButton
{
    LKNavBackButton *button = [[LKNavBackButton alloc] init];
    [button setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setImage:[UIImage imageNamed:@"backArrow"] forState:UIControlStateNormal];
    [button setTitleColor:blueDefault forState:UIControlStateNormal];
    button.bounds = CGRectMake(0, 0, 100, 40);
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    return button;
}

- (void)setType:(NSInteger)type
{
    _type = type;
    if (type == 1) {
        [self setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    } else {
        [self setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    }
}

@end





@interface LKBaseViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIViewControllerTransitioningDelegate>
@property (nonatomic, strong) NSMutableDictionary *heightAtIndexPath;//缓存高度
@property(nonatomic,assign) BOOL pushing;
@end

@implementation LKBaseViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = viewDefualtColor;
    [self setNavgationBackBtn];
    if (@available(iOS 11.0, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}

/**
 设置返回按钮样式
 */
-(void)setNavgationBackBtn{
   self.backButton  = [LKNavBackButton navBackButton];
    [_backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_backButton];
}

- (void)back
{
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
            //push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        //present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    NSString * text = @"暂时还没有相关数据!";
    
    NSDictionary * attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f ],
        NSForegroundColorAttributeName:[UIColor lightGrayColor]};
    
    return [[ NSAttributedString  alloc ] initWithString:text attributes:attributes];
}
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"Nodata"];
}
-(CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
    return 0;
}
-(void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view{
    
    NSLog(@"点击了空白页");

}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -设置图片添加选择的拍照和相册

-(void)showAlertChooseVc{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    [alertVc addAction:takePhotoAction];
    UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushTZImagePickerController];
    }];
    [alertVc addAction:imagePickerAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:cancelAction];
    UIPopoverPresentationController *popover = alertVc.popoverPresentationController;
    [self presentViewController:alertVc animated:YES completion:nil];
}
- (void)takePhoto {
  AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
 if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
    // 无相机权限 做一个友好的提示
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
} else if (authStatus == AVAuthorizationStatusNotDetermined) {
    // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self takePhoto];
            });
        }
    }];
    // 拍照之前还需要检查相册权限
} else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
} else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
    [[TZImageManager manager] requestAuthorizationWithCompletion:^{
        [self takePhoto];
    }];
} else {
    [self pushImagePickerController];
  }
}
    // 调用相机
- (void)pushImagePickerController {
        // 提前定位
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
              UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
              imagePickerController.delegate = (id)self;
              imagePickerController.allowsEditing = NO;
              imagePickerController.sourceType = sourceType;
              imagePickerController.transitioningDelegate = self;
              imagePickerController.modalPresentationStyle = UIModalPresentationCustom;
              [self presentViewController:imagePickerController animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
}
-(void)pushTZImagePickerController{
      TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
      imagePickerVc.allowPickingOriginalPhoto = YES;
      imagePickerVc.allowPickingVideo = NO;
      imagePickerVc.isSelectOriginalPhoto = YES;
      imagePickerVc.sortAscendingByModificationDate = NO;
    if (@available(iOS 13.0, *)) {

    } else {
        imagePickerVc.navigationBar.translucent = NO;
        imagePickerVc.transitioningDelegate = self;
        imagePickerVc.modalPresentationStyle = UIModalPresentationCustom;
    }

    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
//        TZImagePickerController *imagePickervc = (TZImagePickerController *)self.navigationController;
//        UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
//        if (photo) {
//            [[TZImageManager manager] savePhotoWithImage:photo completion:^(PHAsset *asset, NSError *error) {
//            }];
//        }
//    }
//        if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
//            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//            [[TZImageManager manager]savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
//                [self.selectedAssets addObject:asset];
//                [self.selectedPhotos addObject:image];
//                [self.imageCollectionView reloadData];
//                [self layoutNewFrame];
//                if ([self.delegate respondsToSelector:@selector(imagePickerView:didFinishPickPhoto:)]) {
//                    [self.delegate imagePickerView:self didFinishPickPhoto:self.selectedPhotos];
//                }
//            }];
        }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    
}

@end
